package com.techwells.taco.net;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class JsonDataPost {

	//Post�ύ
	public String postData(Map<String, String> params, String encode, String Url) {
        
        byte[] data = getRequestData(params, encode).toString().getBytes();
        try {
        	URL url = new URL(Url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);        
            httpURLConnection.setDoInput(true);              
            httpURLConnection.setDoOutput(true);             
            httpURLConnection.setRequestMethod("POST");       
            httpURLConnection.setUseCaches(false);            
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            /*
            if(null != Constant.PHPSESSID){
            	httpURLConnection.setRequestProperty("Cookie", "_SamsoniteAPI_session=" + Constant.PHPSESSID);
            }
            */
            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(data);
            
            int response = httpURLConnection.getResponseCode();           
            if(response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
                String cookieVal = httpURLConnection.getHeaderField("Set-Cookie");
                if(cookieVal != null){
                	//Constant.PHPSESSID = cookieVal.substring(cookieVal.indexOf("=") + 1, cookieVal.indexOf(";"));
                }
                return dealResponseResult(inptStream);                    
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }  
	
	//Put�ύ
		public String putData(Map<String, String> params, String encode, String Url) {
	        
	        byte[] data = getRequestData(params, encode).toString().getBytes();//���������
	        try {
	        	URL url = new URL(Url);
	            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
	            httpURLConnection.setConnectTimeout(3000);        //�������ӳ�ʱʱ��
	            httpURLConnection.setDoInput(true);               //�����������Ա�ӷ�������ȡ���
	            httpURLConnection.setDoOutput(true);              //����������Ա���������ύ���
	            httpURLConnection.setRequestMethod("PUT");       //������Post��ʽ�ύ���
	            httpURLConnection.setUseCaches(false);            //ʹ��Post��ʽ����ʹ�û���
	            //������������������ı�����
	            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	            /*
	            if(null != Constant.PHPSESSID){
	            	httpURLConnection.setRequestProperty("Cookie", "_SamsoniteAPI_session=" + Constant.PHPSESSID);
	            }
	            */
	            httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
	            //�����������������д�����
	            OutputStream outputStream = httpURLConnection.getOutputStream();
	            outputStream.write(data);
	            
	            int response = httpURLConnection.getResponseCode();            //��÷���������Ӧ��
	            if(response == HttpURLConnection.HTTP_OK) {
	                InputStream inptStream = httpURLConnection.getInputStream();
	                String cookieVal = httpURLConnection.getHeaderField("Set-Cookie");
	                /*
	                if(cookieVal != null){
	                	Constant.PHPSESSID = cookieVal.substring(cookieVal.indexOf("=") + 1, cookieVal.indexOf(";"));
	                }
	                */
	                return dealResponseResult(inptStream);                     //�������������Ӧ���
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return "";
	    }  
	
	//Get�ύ
	public String getData(String Url){       
        try {
        	URL url = new URL(Url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setConnectTimeout(3000);        //�������ӳ�ʱʱ��
            httpURLConnection.setDoInput(true);               //�����������Ա�ӷ�������ȡ���
            httpURLConnection.setDoOutput(true);              //����������Ա���������ύ���
            httpURLConnection.setRequestMethod("GET");        //������Get��ʽ�ύ���
            httpURLConnection.setUseCaches(false);           
            //������������������ı�����
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            //���sessionid��Ϊ�գ��Ͱ�sessionid�������������ñ�����˻�
            /*
            if(null != Constant.PHPSESSID){
            	httpURLConnection.setRequestProperty("Cookie", "_SamsoniteAPI_session=" + Constant.PHPSESSID);
            }
            */
            
            int response = httpURLConnection.getResponseCode();            //��÷���������Ӧ��
            if(response == HttpURLConnection.HTTP_OK) {
                InputStream inptStream = httpURLConnection.getInputStream();
/*                String cookieVal = httpURLConnection.getHeaderField("Set-Cookie");
                //��ȡsession
                if(cookieVal != null){
                	Constant.PHPSESSID = cookieVal.substring(cookieVal.indexOf("=") + 1, cookieVal.indexOf(";"));
                }*/
                return dealResponseResult(inptStream);                     //�������������Ӧ���
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
	
	
	//Delete�ύ
		public String deleteData(String Url){       
	        try {
	        	URL url = new URL(Url);
	            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
	            httpURLConnection.setConnectTimeout(3000);        //�������ӳ�ʱʱ��
	            httpURLConnection.setDoInput(true);               //�����������Ա�ӷ�������ȡ���
	            httpURLConnection.setDoOutput(false);              //����������Ա���������ύ���
	            httpURLConnection.setRequestMethod("DELETE");        //������Get��ʽ�ύ���
	            httpURLConnection.setUseCaches(false);           
	            //������������������ı�����
	            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	            //���sessionid��Ϊ�գ��Ͱ�sessionid�������������ñ�����˻�
	            /*
	            if(null != Constant.PHPSESSID){
	            	httpURLConnection.setRequestProperty("Cookie", "_SamsoniteAPI_session=" + Constant.PHPSESSID);
	            }
	            */
	            int response = httpURLConnection.getResponseCode();            //��÷���������Ӧ��
	            if(response == HttpURLConnection.HTTP_OK) {
	                InputStream inptStream = httpURLConnection.getInputStream();
	                String cookieVal = httpURLConnection.getHeaderField("Set-Cookie");
	                //��ȡsession
	                /*
	                if(cookieVal != null){
	                	Constant.PHPSESSID = cookieVal.substring(cookieVal.indexOf("=") + 1, cookieVal.indexOf(";"));
	                }
	                */
	                return dealResponseResult(inptStream);                     //�������������Ӧ���
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	        return "";
	    }
	
	public StringBuffer getRequestData(Map<String, String> params, String encode) {
		StringBuffer stringBuffer = new StringBuffer(); // �洢��װ�õ���������Ϣ		
		try {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				stringBuffer.append(entry.getKey()).append("=")
						.append(URLEncoder.encode(entry.getValue(), encode))
						.append("&");
			}
			stringBuffer.deleteCharAt(stringBuffer.length() - 1); // ɾ������һ��"&"
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stringBuffer;
	}
    
	public String dealResponseResult(InputStream inputStream) {
		String resultData = null; // �洢������
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		try {
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
			resultData = new String(byteArrayOutputStream.toByteArray());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return resultData;
	}
	
}
